#include "stdafx.h"
#include "global.h"
#include "utf8.h"

BYTE g_proxyAddress[NF_MAX_ADDRESS_LENGTH];
tStrings g_processNames;
std::string g_userName;
std::string g_userPassword;
UserMgr gUserMgr;

std::string trimWhitespace(std::string str)
{
    while (str.length() > 0 && safe_iswhitespace(str[0]))
    {
        str.erase(0, 1);
    }

    while (str.length() > 0 && safe_iswhitespace(str[str.length() - 1]))
    {
        str.erase(str.length() - 1, 1);
    }

    return str;
}

bool parseValue(const std::string &_s, tStrings &v)
{
    std::string sPart;
    size_t pos;
    std::string s = _s;

    v.clear();

    while (!s.empty())
    {
        pos = s.find(",");

        if (pos == std::string::npos)
        {
            sPart = trimWhitespace(s);
            s.erase();
        }
        else
        {
            sPart = trimWhitespace(s.substr(0, pos));
            s.erase(0, pos + 1);
        }

        if (!sPart.empty())
        {
            v.push_back(sPart);
        }
    }

    return true;
}

static std::string getProcessName(DWORD processId)
{
    WCHAR processName[512] = L"";
    WCHAR fullProcessName[512] = L"";
    BOOL nameAcquired = FALSE;

    if (processId == 4)
    {
        return "system";
    }

    nameAcquired = nf_getProcessNameFromKernel(processId, processName, sizeof(processName) / 2);

    if (nameAcquired)
    {
        if (!GetLongPathNameW(processName,
                              fullProcessName,
                              (DWORD)ARRAYSIZE(fullProcessName)))
        {
            wcscpy(fullProcessName, processName);
        }
    }

    return encodeUTF8(fullProcessName);
}

bool checkProcessName(DWORD processId)
{
    std::string processName = getProcessName(processId);

    size_t processNameLen = processName.length();

    for (size_t i = 0; i < g_processNames.size(); i++)
    {
        if (g_processNames[i].length() > processNameLen)
            continue;

        if (_stricmp(g_processNames[i].c_str(),
                     processName.c_str() + processNameLen - g_processNames[i].length()) == 0)
            return true;
    }

    return false;
}
bool stringToIPv6(char *str, char *ipBytes)
{
    int err, addrLen;
    sockaddr_in6 addr;

    addrLen = sizeof(addr);
    err = WSAStringToAddress(str, AF_INET6, NULL, (LPSOCKADDR)&addr, &addrLen);
    if (err < 0)
    {
        return false;
    }

    memcpy(ipBytes, &addr.sin6_addr, NF_MAX_IP_ADDRESS_LENGTH);

    return true;
}